﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;
using System.IO;
using System.Drawing;
using System.Threading;
using OfficeOpenXml.FormulaParsing.Excel.Functions.RefAndLookup;


namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    /// TMS_OA发票交接创建
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class OAInvoiceCreateController : ControllerBase
    {
        private readonly ILogger _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;
        public readonly string con_oa;


        public OAInvoiceCreateController(ILogger<OAInvoiceCreateRequestDto> logger, IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration, ILoggerFactory loggerFactory)
        {
            _WMSTokenCheckService = wmsTokenCheckService;
            con = _configuration.GetConnectionString("DDM_DbConnection_ZH");
            con_oa = _configuration.GetConnectionString("OA_DbConnection");
            _logger = loggerFactory.CreateLogger<OAInvoiceCreateController>();

        }

        /// <summary>
        ///TMS_OA发票交接创建
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostOAInvoiceCreate([FromBody] OAInvoiceCreateRequestDto strparm)
        {
            string  strMsg = "";
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            OAInvoiceCreateResponseDto re = new OAInvoiceCreateResponseDto();

            Dictionary<string, string> dic = new Dictionary<string, string>(); //查询公用dic
            Dictionary<string, string> plandic = new Dictionary<string, string>(); //计划表插入dic

            if (strparm.application_code==""|| strparm.application_code==null)
            {
                strMsg = "application_code不能为空！";
            }

            OA_InvoiceCreateRequestDto data_input = new OA_InvoiceCreateRequestDto();//初始化OA接口数据

            OA_mainDataRequestDto mainData = new OA_mainDataRequestDto();//初始化OA接口数据

            OA_detailDataRequestDto detailData = new OA_detailDataRequestDto();//初始化OA接口数据


            List<OA_detailData_dt2RequestDto> dt2 = new List<OA_detailData_dt2RequestDto>();//分摊明细表赋值

            List<OA_detailData_dt3RequestDto> dt3 = new List<OA_detailData_dt3RequestDto>();//发票明细表赋值

            //抬头参数赋值

            data_input.appId = "246f230d-35f3-4d1246f230dc";
            data_input.userId = "716";
            data_input.workflowId = "2182";



            try
            {
                if (strMsg=="")
                {
                    dic = new Dictionary<string, string>(); //获取
                    dic.Add("Application_code", strparm.application_code);
                    DataTable ft_dt = MethodHelp.GetTableInfo("TMS0164", dic,con);
                    if (ft_dt.Rows.Count>0)
                    {
                        string sqrid = "";//OA人员ID
                        string provision_id = "";//计提流程ID

                        data_input.requestName = ft_dt.Rows[0]["zy"].ToString();


                        //获取人员OAID
                        DataTable hr_ry = DB.MSSQuery("select id from  ecology.dbo.hrmresource  where loginid='"+ ft_dt.Rows[0]["work_no"].ToString() + "' ", con_oa);
                        if (hr_ry.Rows.Count>0)
                        {
                            sqrid = hr_ry.Rows[0]["id"].ToString();

                        }
                        else
                        {
                            strMsg = "工号=<" + ft_dt.Rows[0]["work_no"].ToString() + ">获取OA人员ID失败，请确认后再试！";
                        }

                        //获取计提requestId
                        DataTable jt_dt = DB.MSSQuery("SELECT requestId,lcbh from formtable_main_274  where lcbh='" + ft_dt.Rows[0]["provision_id"].ToString() + "' ", con_oa);
                        if (jt_dt.Rows.Count>0)
                        {
                            provision_id = jt_dt.Rows[0]["requestId"].ToString();
                        }
                        else
                        {
                            provision_id = null;
                        }



                        if (strMsg=="")
                        {
                            data_input.userId = sqrid;

                            //表头数据赋值
                            mainData.sqrq = DB.ToDateTime(ft_dt.Rows[0]["Application_date"].ToString()).Date.ToString("yyyy-MM-dd");
                            mainData.sqr = sqrid;
                            mainData.gh = ft_dt.Rows[0]["work_no"].ToString();
                            mainData.bm = ft_dt.Rows[0]["work_department"].ToString();
                            mainData.gys = ft_dt.Rows[0]["carrier_code"].ToString();
                            mainData.fkdw = ft_dt.Rows[0]["organization_code"].ToString();
                            mainData.lx = ft_dt.Rows[0]["lx"].ToString();
                            mainData.fph = ft_dt.Rows[0]["invoice_no"].ToString();
                            mainData.je = DB.ToDouble(ft_dt.Rows[0]["tax_amount"].ToString());
                            mainData.bz = ft_dt.Rows[0]["currency_type"].ToString();
                            mainData.erpxtsfxdd = ft_dt.Rows[0]["erpxtsfxdd"].ToString();
                            mainData.fyszsybzx = ft_dt.Rows[0]["fyszsybzx"].ToString();
                            mainData.sfsdjfp = ft_dt.Rows[0]["sfsdjfp"].ToString();
                            mainData.gysdd = ft_dt.Rows[0]["gysdd"].ToString();
                            mainData.zffs = ft_dt.Rows[0]["payment_method"].ToString();
                            mainData.jsfs = ft_dt.Rows[0]["payment_termcode"].ToString();
                            mainData.zy = ft_dt.Rows[0]["zy"].ToString();
                            mainData.tjrq = DB.ToDateTime(ft_dt.Rows[0]["condition_date"].ToString()).Date.ToString("yyyy-MM-dd");
                            mainData.hjqj = DB.ToDateTime(ft_dt.Rows[0]["accounting_period"].ToString()).Date.ToString("yyyy-MM-dd");
                            mainData.fprq = DB.ToDateTime(ft_dt.Rows[0]["invoice_date"].ToString()).Date.ToString("yyyy-MM-dd") ;
                            mainData.fyszqj = ft_dt.Rows[0]["invoice_course"].ToString();
                            mainData.fysfyjt = ft_dt.Rows[0]["fysfyjt"].ToString();
                            mainData.gljtlc = provision_id;
                            mainData.jjsx = ft_dt.Rows[0]["jjsx"].ToString();


                            foreach (DataRow item in ft_dt.Rows)
                            {
                                dt2.Add(new OA_detailData_dt2RequestDto
                                {
                                    fyje = DB.ToDouble(item["untax_price"].ToString()),
                                    fygzbm = item["cost_center"].ToString(),
                                    zy = item["zy"].ToString(),
                                    bmbh= item["center_userno"].ToString(),
                                    fygzbmfzr = item["center_user"].ToString(),
                                    km = item["cost_subject"].ToString(),
                                    sdm = item["tax_rate_code"].ToString(),
                                    hjjsrq = DB.ToDateTime(item["cost_date"].ToString()).Date.ToString("yyyy-MM-dd"),
                                    se = item["tax_cost"].ToString(),
                                    sl= item["tax_rate_value"].ToString(),
                                    kmmc = item["cost_subject_name"].ToString()
                                });
                            }


                            dic = new Dictionary<string, string>(); //获取
                            dic.Add("application_code", strparm.application_code);
                            DataTable fp_dt = MethodHelp.GetTableInfo("TMS0165", dic, con);
                            if (fp_dt.Rows.Count>0)
                            {
                                foreach (DataRow row in fp_dt.Rows)
                                {
                                    dt3.Add(new OA_detailData_dt3RequestDto
                                    {
                                        fph = row["invoice_no"].ToString(),
                                        fplx = row["invoice_type"].ToString(),
                                        kdkse = DB.ToDouble(row["untax_price"].ToString()),
                                        bhsje = DB.ToDouble(row["tax_amount"].ToString())

                                    }); ;
                                }
                            }



                            if (dt2.Count>0&&dt3.Count>0)
                            {
                                detailData.formtable_main_367_dt2 = dt2;
                                detailData.formtable_main_367_dt3 = dt3;

                                data_input.mainData = mainData;
                                data_input.detailData = detailData;


                                Dictionary<string, string> urldic = new Dictionary<string, string>(); //URL获取dic
                                urldic.Add("function_description", "OA流程创建");//查看URL配置表地址描述
                                DataTable url_dt = MethodHelp.GetTableInfo("TMS0004", urldic, con);//获取URL地址
                                string jsonText = JsonConvert.SerializeObject(data_input);



                                DateTime requestid_t = DateTime.Now;


                                var reAgv = DB.httpPost(url_dt.Rows[0]["interface_url"].ToString(), jsonText, "", "否");

                                string result_= JsonConvert.SerializeObject(reAgv);

                                //日志记录
                                dic = new Dictionary<string, string>(); //获取
                                dic.Add("Url", url_dt.Rows[0]["interface_url"].ToString());
                                dic.Add("request", jsonText);
                                dic.Add("result", result_);
                                dic.Add("request_time", requestid_t.ToString());
                                MethodHelp.log_create(dic,con);




                                ApiResponse psp = JsonConvert.DeserializeObject<ApiResponse>(reAgv);
                                if (psp.T00003.OA.code!= "SUCCESS")
                                {
                                    strMsg = "发票交接申请=<" + strparm.application_code + ">OA创建失败，原因：<"+ psp.T00003.OA.errMsg.ToString() + ">！";
                                }
                                else
                                {
                                    string oarequestid = psp.T00003.OA.data.requestid.ToString();

                                    dic = new Dictionary<string, string>(); //获取
                                    dic.Add("Application_code", strparm.application_code);
                                    dic.Add("oa_requestid", oarequestid);
                                    strMsg = MethodHelp.InsertIntoTable("TMS0166", dic, con);

                                }


                            }

                        }                      
                    }
                    else
                    {
                        strMsg = "发票交接申请=<"+ strparm.application_code + ">获取不到数据明细，请确认后再试！";
                    }

                }
                












            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }
            if (strMsg=="")
            {
                re.code = 0;
                re.message = "";
            }
            else
            {
                re.code = 500;
                re.message = strMsg;
            }

            _logger.LogInformation(JsonConvert.SerializeObject(re));
            return new JsonResult(re);
        }

      
    }
}
